package com.vedu.user.service.impl;

import com.diandian.util.BeanCopyUtil;
import com.diandian.util.MyUtil;
import com.vedu.constant.Constants;
import com.vedu.user.constants.UserConstants;
import com.vedu.user.dao.UserDao;
import com.vedu.user.entity.bo.UserBo;
import com.vedu.user.entity.po.UserPo;
import com.vedu.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * version: 1.0
 *
 * @author yuancheng.li [create on 2018/8/1 23:51 ]
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createUser(UserBo bo) {

        MyUtil.checkNull(bo, "bo");

        UserPo userPo = BeanCopyUtil.sourceToTarget(bo, UserPo.class);
        UserPo user = userDao.findUserByName(userPo.getLogin());
        if (user != null) {
            throw new RuntimeException("USER EXISTS");
        }

        Date registerDate = new Date();
        userPo.setRegisteredTime(registerDate);
        userPo.setRegisteredDate(new SimpleDateFormat(Constants.DATE_FORMAT).format(registerDate));
        userPo.setState(UserConstants.USER_STATE_NORMAL);
        int count = userDao.insertUser(userPo);

        return count == 1;
    }

    @Override
    public UserBo findUser(String userName, String password) {

        // TODO check param

        UserPo po = userDao.findUserByNameAndPassword(userName, password);

        return BeanCopyUtil.sourceToTarget(po, UserBo.class);
    }

    @Override
    public boolean findUserExists(Integer userId) {

        Integer dbUserId = userDao.findUserId(userId);

        return dbUserId != null;
    }
}
